from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.db.database import get_db
from app.core.security import get_current_admin_user
from app.schemas.user import User, UserBrief, UserUpdate, UserCreate, UserWithStats
from app.crud import user as user_crud

router = APIRouter()

@router.get("/", response_model=List[UserWithStats])
async def list_users(
    skip: int = 0,
    limit: int = 100,
    search: Optional[str] = None,
    status: Optional[str] = None,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """
    管理员获取所有用户列表
    可以通过搜索条件、状态过滤
    """
    users = user_crud.get_users(db, skip=skip, limit=limit, search=search, status=status)
    
    # 添加统计信息
    users_with_stats = []
    for user in users:
        follower_count = len(user_crud.get_followers(db, user_id=user.id))
        following_count = len(user_crud.get_following(db, user_id=user.id))
        post_count = len(user.posts)
        
        user_with_stats = UserWithStats.from_orm(user)
        user_with_stats.follower_count = follower_count
        user_with_stats.following_count = following_count
        user_with_stats.post_count = post_count
        
        users_with_stats.append(user_with_stats)
        
    return users_with_stats

@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(
    user: UserCreate,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """管理员创建用户"""
    db_user = user_crud.get_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="邮箱已被注册")
    
    db_user = user_crud.get_user_by_username(db, username=user.username)
    if db_user:
        raise HTTPException(status_code=400, detail="用户名已被使用")
    
    return user_crud.create_user(db=db, user=user)

@router.get("/{user_id}", response_model=UserWithStats)
async def get_user(
    user_id: int,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """管理员获取指定用户详情"""
    user = user_crud.get_user(db, user_id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 获取统计信息
    follower_count = len(user_crud.get_followers(db, user_id=user_id))
    following_count = len(user_crud.get_following(db, user_id=user_id))
    post_count = len(user.posts)
    
    # 创建带统计信息的用户
    user_with_stats = UserWithStats.from_orm(user)
    user_with_stats.follower_count = follower_count
    user_with_stats.following_count = following_count
    user_with_stats.post_count = post_count
    
    return user_with_stats

@router.put("/{user_id}", response_model=User)
async def update_user(
    user_id: int,
    user_update: UserUpdate,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """管理员更新用户信息"""
    updated_user = user_crud.update_user(db, user_id=user_id, user_update=user_update)
    if not updated_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return updated_user

@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user(
    user_id: int,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """管理员删除用户"""
    # 禁止删除自己
    if current_admin["id"] == user_id:
        raise HTTPException(status_code=400, detail="不能删除自己的账号")
    
    result = user_crud.delete_user(db, user_id=user_id)
    if not result:
        raise HTTPException(status_code=404, detail="用户不存在")
    return {"status": "success", "message": "用户删除成功"}

@router.patch("/{user_id}/status", response_model=User)
async def update_user_status(
    user_id: int,
    status: str,
    current_admin: dict = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """
    管理员更新用户状态
    状态可以是: active, disabled, banned
    """
    if status not in ["active", "disabled", "banned"]:
        raise HTTPException(status_code=400, detail="无效的状态值")
    
    # 禁止更改自己的状态
    if current_admin["id"] == user_id:
        raise HTTPException(status_code=400, detail="不能更改自己的状态")
    
    updated_user = user_crud.update_user_status(db, user_id=user_id, status=status)
    if not updated_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return updated_user 